/**
 * 创建中转数据结构
 * 
 * 模块导出规范遵循 CommonJS
 * 
 */
module.exports={
  createStatementData : function (invoice, plays) {
    const result = {};
    // 顾客信息
    result.customer = invoice.customer;
    // 剧目信息：通过 map 函数遍历 performances，将其属性进行扩展
    result.performances = invoice.performances.map(enrichPerformance);
    // 总费用
    result.totalAmount = totalAmount(result);
    // 总积分
    result.totalVolumeCredits = totalVolumeCredits(result);
    return result;

    /**
     * 计算总费用
     */
    function totalAmount(data) {
      return data.performances
        .reduce((total, p) => total + p.amount, 0);
    }

    /**
     * 计算观众量积分总和
     */
    function totalVolumeCredits(data) {
      return data.performances
        .reduce((total, p) => total + p.volumeCredits, 0);
    }

    /**
     * 将其中每一个 aPerformance 的属性由【playID,audience】 扩展为【playID,audience，play(name,type)】
     * @returns 新增了额外属性的 Performance 对象
     */
    function enrichPerformance(aPerformance) {
      const result = Object.assign({}, aPerformance);
      result.play = playFor(result);
      result.amount = amountFor(result);
      result.volumeCredits = volumeCreditsFor(result);
      return result;
      /**
     * 根据账单中的数据获取对应剧目信息
     * @param {*} aPerformance 
     * @returns 
     */
      function playFor(aPerformance) {
        return plays[aPerformance.playID];
      }

      /**
       * 计算单场剧目的费用
       * @param {*} aPerformance 
       * @returns 
       */
      function amountFor(aPerformance) {
        let result = 0;
        switch (aPerformance.play.type) {
          case "tragedy":
            result = 40000;
            if (aPerformance.audience > 30) {
              result += 1000 * (aPerformance.audience - 30);
            }
            break;
          case "comedy":
            result = 30000;
            if (aPerformance.audience > 20) {
              result += 10000 + 500 * (aPerformance.audience - 20);
            }
            result += 300 * aPerformance.audience;
            break;
          default:
            throw new Error(`unknown type: ${aPerformance.play.type}`);
        }
        return result;
      }
      /**
       * 计算单场剧目产生的观众量积分
       * @param {*} perf 
       * @returns 积分
       */
      function volumeCreditsFor(aPerformance) {
        let result = 0;
        result += Math.max(aPerformance.audience - 30, 0);
        if ("comedy" === aPerformance.play.type) result += Math.floor(aPerformance.audience / 5);
        return result;
      }
    }


  }
}